import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Toast } from 'antd-mobile'
import { serverurl } from '../../utils/request'
import NavHeader from '../../components/NavHeader'
import { getFavoritesAPI, delFavoritesAPI } from '../../api'
import styles from './index.module.css'

function Favorites() {
  const navigate = useNavigate()
  // 小区房源数据
  const [houseList, setHouseList] = useState([])

  // 获取收藏列表数据
  const loadFavorites = async () => {
    const { data: res } = await getFavoritesAPI()
    console.log('收藏列表', res)
    setHouseList(res.body)
  }

  useEffect(() => {
    loadFavorites() // 调用收藏列表数据方法
  }, [])

  // 删除收藏
  const delFavoritesHandler = async (id) => {
    const { data: res } = await delFavoritesAPI(id)

    if (window.confirm('是否确认删除？')) {
      // 1. 提示用户
      Toast.show({
        content: '删除成功',
      })
      // 2. 重新调用收藏列表的方法
      loadFavorites()
      console.log('删除成功', res)
    }
  }

  return (
    <div>
      <NavHeader title="我的收藏"></NavHeader>
      {/* 房屋列表 */}
      <div className={styles.houseList}>
        {houseList.map((item) => (
          <div className={styles.houseItems} key={item.houseCode}>
            {/* 房屋结构 */}
            <div className={styles.house}>
              <div className={styles.imgWrap}>
                <img
                  className={styles.img}
                  src={serverurl + item.houseImg}
                  alt=""
                  onClick={() => navigate(`/detail?id=${item.houseCode}`)}
                />
              </div>
              <div className={styles.content}>
                <h3 className={styles.title}>{item.title}</h3>
                <div className={styles.desc}>{item.desc}</div>
                <div className={styles.tags}>
                  {/* 渲染标签 */}
                  {item.tags.map((tag, index) => {
                    const classTag = 'tag' + (index + 1)
                    return (
                      <span className={[styles[classTag]].join('')} key={tag}>
                        {tag}
                      </span>
                    )
                  })}
                </div>
                <div className={styles.price}>
                  <span className={styles.priceNum}>{item.price}</span> 元/月
                </div>
              </div>

              {/* 删除收藏 */}
              <Button
                color="danger"
                fill="outline"
                size="small"
                className={styles.btn}
                onClick={() => delFavoritesHandler(item.houseCode)}
              >
                删除
              </Button>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default Favorites
